package cn.okcmd.juc;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * create by caoqg on 2021/7/17
 * 功能说明:
 */
@Slf4j
public class TestAtomicFieldUpdate {
    public static void main(String[] args) {
        TestFUObject obj = new TestFUObject();
        AtomicIntegerFieldUpdater<TestFUObject> iau = AtomicIntegerFieldUpdater.newUpdater(TestFUObject.class, "intVal");
        log.info("old obj:[{}]",obj);
        int oldIntVal = iau.get(obj);
        {
            //do some times use ***Seconds
        }
        boolean updateResult = iau.compareAndSet(obj, oldIntVal, 1001);
        log.info("update:{},now obj:[{}]", updateResult, obj);

        AtomicLongFieldUpdater<TestFUObject> lau = AtomicLongFieldUpdater.newUpdater(TestFUObject.class, "longVal");
        long oldLongVal = lau.get(obj);
        {
            //do some times use ***seconds
        }
        updateResult = lau.compareAndSet(obj, oldLongVal, 2001);
        log.info("update:{},now obj:[{}]", updateResult, obj);

        AtomicReferenceFieldUpdater<TestFUObject, String> sau = AtomicReferenceFieldUpdater.newUpdater(TestFUObject.class, String.class, "strVal");
        String oldStrVal = sau.get(obj);
        {
            //do some times use ***seconds
        }
        updateResult = sau.compareAndSet(obj, oldStrVal, oldStrVal+"cqg");
        log.info("update:{},now obj:[{}]", updateResult, obj);



    }
}
